package com.search.examples;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.search.tools.CaffeineTool;
import com.search.tools.MD5EncryptTool;
import com.search.tools.UUIDGeneratorTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

@Slf4j
public class ChaoTuSearch {

    private  static  String url = "https://chaotuyujieapi.cylibyj.com/api/WX/Book/GetIndexBookList";

    private static String token="5F2139E145E44642BD6B5A1A0BAD6466";
    private static String entityStr = "{\"BookName\":\"shuming\",\"IsHave\":0,\"PageIndex\":1,\"ClientType\":\"XCX\",\"NonceStr\":\"suiji\",\"Token\":\""+token+"\",\"Sign\":\"qianming\"}";

    /*private static JSONObject entity;


    static {
        entity = new JSONObject();

    }*/

    public static void main(String[] args) throws UnsupportedEncodingException {
        //post("url");
    }
    //0没书 1有书 -1有书被别人借走了 -2返回数据结构异常
    public static int search(String isbn,String bookName) throws Exception {

        try {
            JSONObject result = post(isbn,bookName,3);
            if(null!=result){
                String code = result.getString("code");
                if("0".equals(code)){
                    JSONObject data = result.getJSONObject("result");
                    if(null!=data){
                        int total = data.getInteger("Count");
                        log.debug("搜索到数量"+total);
                        if(total>0){
                            //log.debug("怎么这么多"+result.toString());
                            JSONArray jsonArray = data.getJSONArray("BookList");
                            for(Object bookObj:jsonArray){
                                JSONObject bookJson = (JSONObject) bookObj;
                                if(isbn.equals(bookJson.get("IsbnCode").toString())){
                                    Object numberObj = bookJson.get("Number");
                                    if(null==numberObj){
                                        return -1;
                                    }
                                    else{
                                        return (int)numberObj;
                                    }
                                }
                            }
                            return 0;
                        }else{
                            return 0;
                        }
                    }else{
                        return -2;
                    }
                }
            }else {
                return -2;
            }
        } catch (Exception e) {
            log.error("搜索出现异常"+isbn+e+e.getMessage());
            throw e;
        } finally {
        }

        return 0;
    }

    public static JSONObject post(String isbn,String bookName,int reTry) throws IOException, InterruptedException {

        String uuidStr = UUIDGeneratorTool.wxuuid();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ClientType","XCX");
        jsonObject.put("NonceStr",uuidStr);
        jsonObject.put("Token",token);
        jsonObject.put("BookName",bookName);
        jsonObject.put("IsHave",0);
        jsonObject.put("PageIndex",1);

        List<String> keys = new ArrayList<>(jsonObject.keySet());
        Collections.sort(keys);

        // 使用LinkedHashMap来保持顺序
        LinkedHashMap<String, Object> orderedMap = new LinkedHashMap<>();
        for (String key : keys) {
            orderedMap.put(key, jsonObject.get(key));
        }

        // 将LinkedHashMap转换为JSONObject（注意：这里只是模拟，因为fastjson2可能不直接支持）
        // 你可能需要以字符串的形式输出，或者再次使用JSON.parseObject(JSON.toJSONString(orderedMap), JSONObject.class)转换回JSONObject
        JSONObject sortedJsonObject = JSON.parseObject(JSON.toJSONString(orderedMap), JSONObject.class);

        StringBuilder builder = new StringBuilder();
        for(String key :sortedJsonObject.keySet()){
            builder.append(key+"="+sortedJsonObject.get(key)+"&");
        }
        builder.append("Key="+token);

        //log.info("签名前"+builder.toString());
        String sign = MD5EncryptTool.encry(builder.toString()).toUpperCase();

        String entity = entityStr.replace("shuming",bookName).replace("qianming",sign).replace("suiji", uuidStr);
        //log.info(bookName+"签名"+sign);
        HttpResponse response ;
        JSONObject result=null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(50000) // 连接超时时间，单位毫秒
                .setSocketTimeout(50000)  // 读取超时时间，单位毫秒
                .build();
        post.setConfig(requestConfig);
        post.setHeader("Sec-Fetch-Dest","empty");
        //post.setHeader("clientinfo","{\"appId\":\"\",\"channel\":\"yuntu-wx-mini\",\"libcode\":\"STL50\"}");
        post.setHeader("Sec-Fetch-Site","cross-site");
        post.setHeader("Host","chaotuyujieapi.cylibyj.com");
        post.setHeader("Accept","*/*");
        post.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090b19)XWEB/9193");
        post.setHeader("xweb_xhr","1");
        post.setHeader("jwt","");
        post.setHeader("Accept-Language","zh-CN,zh;q=0.9");
        post.setHeader("Accept-Encoding","gzip, deflate, br");
        post.setHeader("Sec-Fetch-Mode","cors");
        post.setHeader("Content-Type","application/json");
        post.setHeader("Referer","https://servicewechat.com/wxc38c4fa25d10df3f/143/page-frame.html");
        post.setHeader("Connection","keep-alive");

        post.setEntity(new StringEntity(entity, ContentType.APPLICATION_JSON));

        try{
            response = httpclient.execute(post);
            String body = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
            result = JSONObject.parseObject(body);
            //System.out.println(result);
            log.info(isbn+bookName+"搜索结果"+result.toString());

        }catch (Exception e){
            log.error("请求图书馆接口出错"+e.toString());
            e.printStackTrace();
            if(reTry>0){
                Thread.sleep(3000);
                return post(isbn,bookName,reTry-1);
            }else{
                throw e;
            }

        }


        return result;
    }


}
